import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {path: '/',  redirect:'/manager/home'},
    {path: '/manager',  component: () => import('../views/Manager.vue'),
          children:[
          {path: 'home', component: () => import('../views/Home.vue')},
          {path: 'admin', component: () => import('../views/Admin.vue')},
          {path: 'user', component: () => import('../views/User.vue')},
          {path: 'ai-chat', component: () => import('../views/AIChat.vue')},
          {path: 'task-publish', component: () => import('../views/TaskPublish.vue')},
          {path: 'task-list', component: () => import('../views/TaskList.vue')},
          {path: 'notice', component: () => import('../views/Notice.vue')},
          ]
    },
    {path: '/notfound', name: 'notFound', component: () => import('../views/404.vue')},
    {path: '/login', name: 'login', component: () => import('../views/Login.vue')},
    {path: '/register', name: 'register', component: () => import('../views/Register.vue')},
    {path: '/:pathMatch(.*)',redirect:'/notfound'}
  ],
})
// 路由白名单，不需要登录就可以访问
const whiteList = ['/login', '/register', '/notfound']

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')

  // 有token或者在白名单中可以直接访问
  if (token || whiteList.includes(to.path)) {
    next()
  } else {
    // 没有token且不在白名单中，重定向到登录页
    next(`/login?redirect=${to.path}`)
  }
})

export default router
